package com.com.effectivejava.generalprogramming;

import java.math.BigDecimal;

/**
 * Created by User on 09/07/2014.
 */
public class AvoidUsingFloatOrDouble {

   // Notes.
    /*
    If the quantities don’t exceed nine
    decimal digits, you can use  int ; if they don’t exceed eighteen digits, you can use
    long . If the quantities might exceed eighteen digits, you must use  BigDecimal
   */

    // Broken - uses floating point for monetary calculation!
    public static void main(String[] args) {
        brokenFloatArithmetic();
        useBigDecimal();
    }

    // Use BigDecimal instead.
    public static void useBigDecimal(){
        final BigDecimal TEN_CENTS = new BigDecimal(".10");

        BigDecimal funds = new BigDecimal(1.00);
        int itemsBought = 0;

        for(BigDecimal price = TEN_CENTS; funds.compareTo(price)>=0; price=price.add(TEN_CENTS)){
            itemsBought++;
            funds = funds.subtract(price);
        }
        System.out.println(itemsBought + " items bought.");
        System.out.println("Money left over: $" + funds);
    }

    // Dont use floats or doubles.
    public static void brokenFloatArithmetic(){
        double funds = 1.00;
        int itemsBought = 0;
        for (double price = .10; funds >= price; price += .10) {
            funds -= price;
            itemsBought++;
        }
        System.out.println(itemsBought + " items bought.");
        System.out.println("Change: $" + funds);
    }

}
